#define UNW_LOCAL_ONLY
#include <stdio.h>
#include <stdlib.h>
#include "libunwind.h"
#include <android/log.h>

#define LOG_TAG "Backtrace"
#define LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)

void func_backtrace(void)
{
    unw_context_t ctx = {0};
    unw_cursor_t cursor = {0};
    unw_word_t offset = 0;
    unw_word_t pc = 0;
    int8_t func_name[128] = {0};
    int32_t ret = 0;

    LOGD("\n----------------------stack backtrace----------------------------\n");

    ret = unw_getcontext(&ctx);
    if(0 != ret)
    {
        LOGD("get context failed\n");
        return;
    }

    ret = unw_init_local(&cursor, &ctx);
    if(0 != ret)
    {
        LOGD("init local cursor failed\n");
        return;
    }

    while(0 < unw_step(&cursor))
    {
        ret = unw_get_proc_name(&cursor, reinterpret_cast<char *>(func_name), sizeof(func_name), &offset);
        if(0 != ret)
        {
            unw_get_reg(&cursor, UNW_REG_IP, &pc);
            LOGD("0x%lx: can not get func name\n",pc);
        }
        else
        {
            unw_get_reg(&cursor, UNW_REG_IP, &pc);
            LOGD("0x%lx:(%s+0x%lx)\n", pc, func_name, offset);
        }
    }

}
